import React, { Component } from 'react'
import { observable, action, computed } from 'mobx'

export default class cartStore {
  @observable items = []
  @observable foo = 'baz'

  @action.bound addToCart (productObj) {
    console.log('addToCart')
    const prod = this.items.find(cartItem => {
      return cartItem.id === productObj.id
    })
    if (prod) {
      prod.quantity++
    } else {
      this.items.push({
        ...productObj,
        quantity: 1
      })
    }
    // 添加完购物车商品以后，需要让商品列表中的库存数据 -1
    this.rootStore.productsStore.decrementInventory(productObj)
  }

  @computed get totalPrice () {
    const value = this.items.reduce((accumulator, currentValue, currentIndex, array) => {
      console.log(accumulator, currentValue, currentIndex, array)
      return accumulator + currentValue.price * currentValue.quantity
    }, 0)
    console.log(value)
    return value
  }



  constructor (rootStore) {
    this.rootStore = rootStore
  }
}
